package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class FriendsTimeline extends Activity {
	
	private static final int ID_REFRESH = 0;
	private static final int GROUP1 = 1;
	DefaultHttpClient httpclient;
	String username,password;
	private GetFriendsTLTask friendsTLTask;
	ArrayList<String> friendsPhotos;
	private boolean threadRunning = false;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"FriendsTimeline : onCreate");
		setContentView(R.layout.friendstimeline);

		httpclient = new DefaultHttpClient();
		Cookie cookie = Common.recupCookie(this);
		httpclient.getCookieStore().addCookie(cookie);
		httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);

		Bundle bundle = getIntent().getExtras();
		username = bundle.getString("username");
		password = bundle.getString("password");
		
		if(savedInstanceState==null){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"Downloading friends timeline");
			findViewById(R.id.friendsLoadingLinear).setVisibility(View.VISIBLE);
			friendsTLTask = new GetFriendsTLTask();
			friendsTLTask.setActivity(this);
			friendsTLTask.execute();
		}else{
			if(getLastNonConfigurationInstance()!=null){
				friendsTLTask=(GetFriendsTLTask) getLastNonConfigurationInstance();
				friendsTLTask.setActivity(this);
			}else{
				friendsPhotos = savedInstanceState.getStringArrayList("friendsPhotos");
				if(friendsPhotos!=null && friendsPhotos.size()>0) 
					displayPhotos(true);
				else
					displayPhotos(false);
			}
		}
	}
	
	protected void onSaveInstanceState(Bundle outState) {
		if(Common.HIGHDEBUG)
			Log.i(Common.TAG,"FriendsTimeline : onSaveInstantState");
		outState.putStringArrayList("friendsPhotos",friendsPhotos);
	}
	
	public Object onRetainNonConfigurationInstance() {
		if(friendsTLTask!=null){
			friendsTLTask.setActivity(null);
		}
		return friendsTLTask;
	}
	
	private void fillTimelineArray(String reponse){
		friendsPhotos = new ArrayList<String>();
		try {
			JSONArray jTimeline = new JSONArray(reponse);
			if(jTimeline.length()>0){
				for(int i=0;i<jTimeline.length();i++){
					friendsPhotos.add(jTimeline.getString(i));
				}
				displayPhotos(true);
			}else
				displayPhotos(false);
		} catch (JSONException e) {
			displayPhotos(false);
		}
	}
	
	private void displayPhotos(boolean photosOK){
		findViewById(R.id.friendsLoadingLinear).setVisibility(View.GONE);
		if(photosOK){
			findViewById(R.id.listFriendsTLPhotos).setVisibility(View.VISIBLE);
			findViewById(R.id.friendsErrorTimeline).setVisibility(View.GONE);
			ListView friendsList = (ListView)findViewById(R.id.listFriendsTLPhotos);
			FriendsTimelineAdapter friendsTimeline = new FriendsTimelineAdapter(this,friendsPhotos);
			friendsList.setAdapter(friendsTimeline);
			setOnClickPhotos(friendsList);
		}else{
			findViewById(R.id.friendsErrorTimeline).setVisibility(View.VISIBLE);
		}
	}
	
	private void setOnClickPhotos(ListView friendsList){
		friendsList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
				JSONObject jPicture;
				try {
					jPicture = new JSONObject(friendsPhotos.get(position));
					String photoURL = Common.getBaseImgsUrl()+jPicture.getString("url");
					Intent i = new Intent(FriendsTimeline.this,FullscreenPicture.class);
					i.putExtra("uri", photoURL);
					startActivity(i);
				} catch (JSONException e) {
				}
			}
		});
	}
	
	private void onThreadCompleted(Bundle data){
		if(!data.containsKey("eMessage")){
			if(Common.HIGHDEBUG)
				Log.d(Common.TAG,"onThreadCompleted");
			fillTimelineArray(data.getString("reponse"));
		}else{
			Toast erreurToast = Toast.makeText(FriendsTimeline.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
		setThreadRunning(false);
	}
	
	private class GetFriendsTLTask extends AsyncTask<String,String,Message>{
		private FriendsTimeline activity;
		private boolean completed=false;
		private Message msg;

		protected Message doInBackground(String... parameters) {
			Message msg = Message.obtain();
			Bundle data = new Bundle();
			String urlTimeline = Common.getBaseUrl()+"/friendstimeline";
			String reponse = null;
			setThreadRunning(true);
			try {
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("user", username));
				params.add(new BasicNameValuePair("password", password));
				reponse = Common.postUrlData(httpclient, urlTimeline,params);
				data.putString("reponse",reponse);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			msg.setData(data);
			return msg;
		}

		protected void onPostExecute(Message msg) {
			completed=true;
			this.msg=msg;
			if(activity!=null)
				endTask(msg);
		}

		private void setActivity(FriendsTimeline activity) {
			this.activity = activity;
			if ( completed ) {
				endTask(msg);
			}
		}

		private void endTask(Message msg){
			activity.friendsTLTask=null;
			activity.onThreadCompleted(msg.getData());
		}
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(GROUP1, ID_REFRESH, 0, getString(R.string.refresh)).setIcon(R.drawable.ic_menu_refresh);
		return true;
	}
	
	@Override
	  public boolean onPrepareOptionsMenu(Menu menu)
	  {
	      super.onPrepareOptionsMenu(menu);

	      MenuItem item = menu.findItem(ID_REFRESH);
	      if(isThreadRunning()){
	    	   item.setEnabled(false);
	      }
	      else
	    	  item.setEnabled(true);
	   

	      return true;
	  }
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case ID_REFRESH:
			if(Common.HIGHDEBUG)
				Log.i(Common.TAG,"Refresh Friends timeline");
			refreshTimeline();
		}
		return false;
	}

	public void refreshTimeline(){
		if(Common.HIGHDEBUG)
			Log.d(Common.TAG,"Downloading friends timeline");
		findViewById(R.id.listFriendsTLPhotos).setVisibility(View.GONE);
		findViewById(R.id.friendsLoadingLinear).setVisibility(View.VISIBLE);
		friendsTLTask = new GetFriendsTLTask();
		friendsTLTask.setActivity(this);
		friendsTLTask.execute();
	}

	public boolean isThreadRunning() {
		return threadRunning;
	}

	public void setThreadRunning(boolean threadRunning) {
		this.threadRunning  = threadRunning;
	}
}
